<?php 
/***create by  fu 
 * 要想使用必须在config 里面配置 exception_handle
 */

namespace app\lib\exception;

use think\exception\Handle;
use think\Exception;
use think\Request;
use think\Log;
/**
* 
*/
class ExceptionHandler extends Handle
{
	private $code;
	private $msg;
	private $errorCode;
	//需要返回客户端当前请求的url路径

	/**重写Handle 的render方法
	 * 当下使用了根命名空间的 Exception  而不是think\Exception 因为 httpException也是继承根命名空间的Exception
	 */
	public function render(\Exception $e)
	{
		//如果是用户行为导致的异常
		if ($e instanceof BaseException) {
			//如果是自定义的异常
			$this->code = $e->code;
			$this->msg = $e->msg;
			$this->errorCode = $e->errorCode;
		}else{
			
			if(config('app_debug'))
			{
				return parent::render($e);
			}
			else
			{
				$this->code = 500;
				$this->msg = '服务器内部错误';
				$this->errorCode = 999;
	            //记录日志
	            $this->recordErrorLog($e);
			}
			
		}
		$request = Request::instance();

		$result = [
			'msg'=>$this->msg,
			'error_code'=>$this->errorCode,
			'request_url'=>$request->url(),
		];

		return json($result,$this->code);


	}

	private function recordErrorLog(\Exception $e)
	{
		Log::init([
		    'type'  =>  'File',
		    // 日志保存目录
	        'path'  => LOG_PATH,
	        // 日志记录级别
	        'level' => ['error'],
		]);
		Log::record($e->getMessage(),'error');
	}
	
	 
}












 ?>